<%@ page contentType="text/html;charset=UTF-8" %>
<%@ include file="../../include/tag.jsp" %>
<!DOCTYPE html>
<html lang="zh">
<head>
    <title>绑定商户信息</title>
    <%@include file="../../include/commonFile.jsp" %>
    <%--<link rel="stylesheet" href="${ctx}/css/common/list.css">--%>
    <link rel="stylesheet" href="${ctx}/css/ui/system/member/member_form.css">
    <style type="text/css">
        #headImg_img.cover-img {
            width: 80px !important;
            height: 80px !important;
        }

        #qrUrl_img.cover-img {
            width: 150px !important;
            height: 150px !important;
        }

        .layui-tab-brief > .layui-tab-title .layui-this {
            color: #e8473f !important;
        }

        .layui-tab-brief > .layui-tab-title .layui-this:after {
            border-bottom-color: #e8473f !important;
        }

        #mchForm .layui-form-item .layui-input-inline {
            width: 280px !important;
        }
    </style>
</head>
<body>
<!--头部-->
<%@include file="../../include/header.jsp" %>
<div class="index-outside">
    <%@include file="../../include/sidebar.jsp" %>
    <!--内容-->
    <section>
        <div class="section-main">

            <form id="mchForm" class="layui-form mt20" method="post" action="${ctx}/system/member/bindMerchant.do">
                <input type="hidden" name="id" value="${memberMerchant.id}"/>
                <input type="hidden" name="memberId" value="${member.id}"/>
                <input type="hidden" id="from" value="${from}"/>
                <input type="hidden" id="authorizationSuccess" value="<c:choose><c:when test="${grantor != null}">1</c:when>
                        <c:otherwise>0</c:otherwise></c:choose>"/>
                <div class="layui-form-item">
                    <div class="layui-inline">
                        <label class="layui-form-label">配置方式<span class="f-verify-red">*</span></label>
                        <div class="layui-input-inline">
                            <input type="radio" name="deployType" value="0" lay-filter="deploy_type"
                                   title="授权配置" ${member == null ||member.deployType == '0' ? 'checked="checked"' : ''}/>
                            <input type="radio" name="deployType" value="1" lay-filter="deploy_type"
                                   title="填写配置" ${member != null && member.deployType == '1' ? 'checked="checked"' : ''} />
                        </div>
                    </div>
                </div>
                <%--<div class="layui-form-item">
                    <div class="layui-inline">
                        <label class="layui-form-label">是否启用</label>
                        <div class="layui-input-inline">
                            <input type="radio" name="openStatus" value="1" title="是" ${member != null && member.openStatus == '1' ? 'checked="checked"' : ''} />
                            <input type="radio" name="openStatus" value="0" title="否" ${member == null || member.openStatus == '0' ? 'checked="checked"' : ''} />
                        </div>
                    </div>
                </div>--%>
                <div class="layui-form-item">
                    <div class="layui-inline">
                        <label class="layui-form-label">强制关注</label>
                        <div class="layui-input-inline">
                            <input type="radio" name="mandatoryAttention" value="1"
                                   title="是" ${member != null && member.mandatoryAttention == '1' ? 'checked="checked"' : ''} />
                            <input type="radio" name="mandatoryAttention" value="0"
                                   title="否" ${member == null || member.mandatoryAttention == '0' || member.mandatoryAttention == null ? 'checked="checked"' : ''} />
                        </div>
                    </div>
                </div>

                <div class="layui-form-item">
                    <div class="layui-inline">
                        <label class="layui-form-label">微信账户<span class="f-verify-red">*</span></label>
                        <div class="layui-input-inline">
                            <select name="externalAccountId" id="externalAccountId" lay-verify="externalAccountId"
                                    lay-filter="externalAccountId"
                                    <c:if test="${member != null && member.deployType == '0'}">disabled=disabled</c:if>>
                                <option value=""><c:if test="${member != null && member.deployType == '0'}">用户未授权</c:if><c:if
                                        test="${member != null && member.deployType == '1'}">请选择</c:if></option>
                                <c:forEach var="wechat" items="${wechatOpenMemberList}">
                                    <option value="${wechat.id}" ${wechat.id == memberExternalApp.externalAccountId ? 'selected="selected"' : ""}>${wechat.nickName}</option>
                                </c:forEach>
                            </select>
                        </div>
                    </div>
                </div>

                <%--<div class="layui-form-item" id="authorization">
                    <div class="layui-inline">
                        <label class="layui-form-label">去微信授权</label>
                        <div class="layui-input-inline">
                            <a href="${ctx}/openPlatform/authorization/getAuthorizeUrl.do?memberId=${member.id}" class="layui-btn layui-btn layui-btn-danger f14" >立刻绑定</a>
                        </div>
                    </div>
                </div>--%>

                <div class="layui-form-item">
                    <div class="layui-inline">
                        <label class="layui-form-label">商户账户<span class="f-verify-red">*</span></label>
                        <div class="layui-input-inline">
                            <select name="externalMerchantId" id="externalMerchantId" lay-verify="externalMerchantId"
                                    lay-filter="externalMerchantId">
                                <c:forEach var="merchants" items="${wechatMerchantsList}">
                                    <option value="${merchants.id}" ${merchants.id == memberExternalApp.externalMerchantId ? 'selected="selected"' : ""}>${merchants.merchantName}</option>
                                </c:forEach>
                            </select>
                        </div>
                    </div>
                </div>

                <input type="hidden" id="resUrl" value="${testPayUrl}"/>
                <div class="layui-form-item">
                    <label class="layui-form-label">扫码检查配置</label>
                    <input id="testPayUrl" name="testPayUrl" type="hidden"/>
                    <div class="layui-input-block"><div id="qrcode"></div></div>
                </div>

                <div class="layui-form-item">
                    <div class="layui-input-block">
                        <a href="javascript:void(0)" class="layui-btn layui-btn-danger" lay-submit lay-filter="mchForm">立即保存</a>
                        <a href="${ctx}/system/member/partnerList.do" class="layui-btn layui-btn-primary">取消</a>
                    </div>
                </div>
            </form>
        </div><!--底部-->
        <%@include file="../../include/footer.jsp" %>
    </section>
</div>
<script type="text/javascript" src="${ctxStatic}/jquery.qrcode/jquery.qrcode.min.js"></script>
<script>
    $(function () {
        layui.use(['form', 'laydate', 'element'], function () {
            var form = layui.form, laydate = layui.laydate, element = layui.element;

            form.verify({
                externalAccountId: function (value) {
                    if (value == null || value == "") {
                        var params = $('#mchForm').serialize();
                        var deployTypeNew = params.substr(params.indexOf("deployType=") + "deployType=".length, 1);
                        if (deployTypeNew == 1) {
                            return "请选择微信账户";
                        } else {
                            return "请先联系用户授权";
                        }
                    }
                },
                externalMerchantId: function (value) {
                    if (value == null || value == "") {
                        return "请选择商户账户";
                    }
                }
            });

            form.on('radio(deploy_type)', function (data) {
                var inviteRadioValue = data.value;
                loadWechat(inviteRadioValue);
            });

            //监听提交 绑定商户信息
            form.on('submit(mchForm)', function (data) {
                txz.submitObject(data.elem, function (callBack) {
                    var action = $("#mchForm").attr("action");
                    $.post(action, $('#mchForm').serialize(), function (res) {
                        typeof callBack === 'function' && callBack();
                        if (res.success) {
                            util.layerMsgSuccess("商户信息保存成功", function () {
                                window.location.href = "${ctx}/system/member/partnerList.do";
                            });
                        }
                        else {
                            util.layerMsgError(res.description)
                        }
                    })
                });
                return false;
            });

            form.on('select(externalAccountId)', function () {
                selectClick('wechatOpenMemberId', $("#externalAccountId").val());
                myQrcode($("#testPayUrl").val());
            });

            form.on('select(externalMerchantId)', function () {
                selectClick('wechatMerchantId', $("#externalMerchantId").val());
                myQrcode($("#testPayUrl").val());
            });

            function loadWechat(deployType) {
                $.post("${ctx}/wechat/account/findByDeployType.do", {
                    "deployType": deployType,
                    "memberId": '${member.id}'
                }, function (data) {
                    var wechatOpenMemberListNew = data.data.wechatOpenMemberList;
                    var wechatMerchantsListNew = data.data.wechatMerchantsList;
                    var array = new Array();
                    if (deployType == 0) {
                        array.push("<option value = ''>用户未授权</option>");
                    } else if (deployType == 1) {
                        array.push("<option value = ''>请选择</option>");
                    }
                    for (var i = 0; i < wechatOpenMemberListNew.length; i++) {
                        if ('${memberExternalApp.externalAccountId }' == wechatOpenMemberListNew[i].id) {
                            array.push("<option value = '" + wechatOpenMemberListNew[i].id + "' selected='selected'>" + wechatOpenMemberListNew[i].nickName + "</option>");
                        } else {
                            array.push("<option value = '" + wechatOpenMemberListNew[i].id + "'>" + wechatOpenMemberListNew[i].nickName + "</option>");
                        }
                    }
                    $("#externalAccountId").empty();
                    if (deployType == 0 && array.length < 2) {
                        $("#externalAccountId").attr("disabled", "disabled");
                        authorizationShow(true);
                    } else if (deployType == 0 && array.length >= 2) {
                        $("#externalAccountId").attr("disabled", "disabled");
                        array.splice(0, 1);
                        authorizationShow(false);
                    } else {
                        $("#externalAccountId").removeAttr("disabled");
                        authorizationShow(false);
                    }
                    $("#externalAccountId").append(array.join(""));

                    array = new Array();
                    for (var i = 0; i < wechatMerchantsListNew.length; i++) {
                        if ('${memberExternalApp.externalMerchantId }' == wechatMerchantsListNew[i].id) {
                            array.push("<option value = '" + wechatMerchantsListNew[i].id + "' selected='selected'>" + wechatMerchantsListNew[i].merchantName + "</option>");
                        } else {
                            array.push("<option value = '" + wechatMerchantsListNew[i].id + "'>" + wechatMerchantsListNew[i].merchantName + "</option>");
                        }
                    }
                    $("#externalMerchantId").empty();
                    $("#externalMerchantId").append(array.join(""));
                    form.render('select');
                    selectClick('wechatOpenMemberId', $("#externalAccountId").val());
                    selectClick('wechatMerchantId', $("#externalMerchantId").val());
                    selectClick('deployType', deployType);
                    myQrcode($("#testPayUrl").val());
                });
            }

            function authorizationOrNot() {
                if ($("#from").val() == 'authorization') {
                    var authorizationSuccess = $("#authorizationSuccess").val();
                    if (0 == authorizationSuccess) {
                        util.layerMsgError("授权失败, 请重新授权")
                    } else if (1 == authorizationSuccess) {
                        util.layerMsgSuccess("授权成功")
                    }
                }
            }

            authorizationOrNot();
        });
        startInit();
    });

    function startInit() {
        var accountId = $("#externalAccountId").val();
        var merchantId = $("#externalMerchantId").val();
        if (accountId == null || accountId == "" || merchantId == null || merchantId == "") {
            return;
        }
        var testPayUrl = $("#testPayUrl").val();
        if (testPayUrl == null || testPayUrl == "") {
            testPayUrl = $("#resUrl").val();
        }
        var deployType = $("input[name='deployType']:checked").val();
        testPayUrl += "?wechatOpenMemberId=" + accountId + "&wechatMerchantId=" + merchantId + "&deployType=" + deployType;
        $("#testPayUrl").val(testPayUrl);
        myQrcode(testPayUrl);
        if (deployType == 0 && (accountId == null || accountId == undefined || accountId == '')) {
            authorizationShow(true);
        } else {
            authorizationShow(false);
        }
    }

    function selectClick(name, value) {
        var accountId = $("#externalAccountId").val();
        var merchantId = $("#externalMerchantId").val();
        if (accountId == null || accountId == "" || merchantId == null || merchantId == "") {
            $("#testPayUrl").val("");
            $('#qrcode').html('');
            return;
        }
        var testPayUrl = $("#testPayUrl").val();
        if (testPayUrl == null || testPayUrl == "") {
            testPayUrl = $("#resUrl").val();
        }
        if (testPayUrl.indexOf("?") < 0) {
            var deployType = $("input[name='deployType']:checked").val();
            testPayUrl += "?" + "deployType=" + deployType + "&" + name + "=" + value;
        } else {
            testPayUrl = changeURLArg(testPayUrl, name, value);
        }
        $("#testPayUrl").val(testPayUrl);

    }

    function myQrcode(testPayUrl) {
        $.post("${ctx}/qrcode/qrcode/convertLink.do", {"longUrl":testPayUrl}, function (res) {
            if(res.success) {
                $('#qrcode').html('');
                $('#qrcode').qrcode({
                    width: 150,
                    height: 150,
                    render: "canvas",
                    text: res.data
                });
            } else {
                util.layerMsgError('二维码加载失败');
            }
        })
    }

    function changeURLArg(url, name, value) {
        var pattern = name + '=([^&]*)';
        var replaceText = name + '=' + value;
        if (url.match(pattern)) {
            var tmp = '/(' + name + '=)([^&]*)/g';
            tmp = url.replace(eval(tmp), replaceText);
            return tmp;
        } else {
            if (url.match('[\?]')) {
                return url + '&' + replaceText;
            } else {
                return url + '?' + replaceText;
            }
        }
    }

    function authorizationShow(authorization) {
        var authorizationBtn = $("#authorization");
        if (authorization) {
            authorizationBtn.removeAttr("hidden");
        } else {
            authorizationBtn.attr("hidden", "hidden");
        }
    }
</script>
</body>
<script type="text/javascript">
    txz.initHeader({
        nav: [{
            name: '合作商管理',
            href: '${ctx}/system/member/partnerList.do'
        }, {
            name: '${member.realname}',
            href: 'javascript:history.back();'
        }, {
            name: '绑定商户信息',
            curr: true
        }],
        btns: [{
            name: '返回',
            href: 'javascript:history.back();',
            icon: 'back'
        }]
    });
</script>
</html>